AE = typeof AE !== 'undefined' ? AE : {};
AE.Helper = (function() {
    var Helper = {
        mergeObject : function() {
            var objs = Array.prototype.slice.call(arguments, 0),
                i, obj, p, ret = {};
            objs.forEach(function(obj) {
                for (p in obj) {
                    if (obj.hasOwnProperty(p)) {
                        ret[p] = obj[p];
                    }
                }
            });

            return ret;
        },

        buildURI : function() {
            var args = Array.prototype.slice.call(arguments);
            if (args.length < 2) {
                return args[0] || "";
            }

            var uri = args.shift(),
                params = args.join("&").replace(/&+/g, "&");

            if (params) {
                uri += (uri.indexOf("?") > 0 ? "&" : "?") + params;
            }

            return uri;
        },

        toQueryString : function(obj) {
            obj = obj || {};
            var parts = [];
            for (var p in obj) {
                if (obj.hasOwnProperty(p)) {
                    parts.push(p + "=" + encodeURIComponent(obj[p]));
                }
            }

            return parts.join("&");
        },

        /**
         * Send a xhr request
         * @param   {Object}    config
         */
        makeRequest : function(config) {
            if (!config) {
                return null;
            }
            var method = config.method || "POST",
                url = config.url,
                headers = config.headers || {},
                callback = config.callback,
                params = config.params || "",
                data = config.data || "";

            if (!url || !callback) {
                return null;
            }

            if (params instanceof Object) {
                params = Helper.toQueryString(params);
            }

            if (data instanceof Object) {
                data = Helper.toQueryString(data);
            }

            var xhr = new XMLHttpRequest();

            callback = (function(x, cb) {
                return function() { cb(x); };
            })(xhr, callback);

            url = Helper.buildURI(url, params);

            xhr.open(method, url, true);
            for (var p in headers) {
                xhr.setRequestHeader(p, headers[p]);
            }
            xhr.setRequestHeader("Origin", "");
            xhr.onreadystatechange = callback;
            xhr.send(data);
            return xhr;
        },

        format : function(fmt, obj) {
            return fmt.replace(/\{(\w+)\}/g, function(src, key) {
                return (key in obj) ? (obj[key] + "") : "";
            });
        }
    };

    return Helper;
})();